import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:uteped_sdk/uteped_sdk.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  bool isBluetoothEnable = false;
  final _utepedSdkPlugin = UTEPedSdk();
  final _eventChannel = const EventChannel('uteped_sdk/event');

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _utepedSdkPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 通讯测试
    _eventChannel.receiveBroadcastStream().listen((event) {
      print("Flutter:Flutter receive from Android:$event");
      if (event["method"] == "connect" && event["status"] == 2) {
        getDeviceInfo().then((value) => debugPrint(value.toString()));
      }
    }, onDone: () {
      print("完成");
    }, onError: (error) {
      print("失利：$error");
    });

    bool isSupportBle4_0 = false;
    try {
      isSupportBle4_0 = await _utepedSdkPlugin
          .bFunc({"path": "device", "method": "isBluetoothEnable"});
      // await _utepedSdkPlugin.vFunc({"path": "device", "method": "connect", "address": "78:02:B7:DA:5B:09"});
    } on PlatformException {
      isSupportBle4_0 = false;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
      isBluetoothEnable = isSupportBle4_0;
    });
  }

  Future<String?> getPlatformVersion() async{
    String platformVersion;
    try {
      platformVersion = await _utepedSdkPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    return platformVersion;
  }

  Future<void> connect() async {
    ///
    // await _utepedSdkPlugin
    //     .bFunc({"path": "device", "method": "connect", "address": "78:02:B7:13:00:C1", "userId": "da58ee730c04651a"});
    await _utepedSdkPlugin
        .vFunc({"path": "device", "method": "scanDevice"});
  }

  Future<void> test() async {
    ///
    print('getWatchFaceOnlineInformation@@@  =====>>> : start');
    String map = '{"languageType":"zh", "refresh":"false"}';
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "getWatchFaceOnlineInformation", 'type': map});
    print('getWatchFaceOnlineInformation###  =====>>> : $info');
  }

  Future<Map<dynamic, dynamic>> getDeviceInfo() async {
    var info = await _utepedSdkPlugin
        .dFunc({"path": "device", "method": "getDeviceInfo"});

    return info;
  }

  Future<void> _scanDevice() async {
    if (!isBluetoothEnable) {
      print("bluetooth not enabled!");
      return;
    }
    try {
      await _utepedSdkPlugin
          .bFunc({"path": "device", "method": "scanDevice", "type": "list"});
    } on PlatformException {
      print("e");
    }
  }

  Future<void> download() async {
    print('download@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "downloadFile", 'type': 'https://update.ute-tech.com.cn/watch/all/all/resource/1703470384_4575.bin'});
    print('download###  =====>>> : $info');
  }

  Future<void> uploadWatchFace() async {
    print('uploadWatchFace@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "uploadWatchFace", 'type': 'https://update.ute-tech.com.cn/watch/all/all/resource/1703470384_4575.bin'});
    print('uploadWatchFace###  =====>>> : $info');
  }

  Future<void> applyWatchFace() async {
    print('applyWatchFace@@@  =====>>> : start');
    String map = '{"id":"9024001", "version":"1.0.0", "operate":"1"}';
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "applyWatchFace", 'type': map});
    print('applyWatchFace###  =====>>> : $info');
  }

  Future<void> getWatchFaceInfo() async {
    print('getWatchFaceInfo@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "getWatchFaceInfo"});
    print('getWatchFaceInfo###  =====>>> : $info');
  }

  Future<void> getWatchFaceParams() async {
    print('getWatchFaceParams@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "getWatchFaceParams"});
    Map<dynamic, dynamic> map = jsonDecode(info);
    print('getWatchFaceParams###  =====>>> : $info/${map['mErrorCode']}');
  }

  Future<void> permissions() async {
    print('permissions@@@  =====>>> : start');

    List<String> permissions = ['android.permission.WRITE_EXTERNAL_STORAGE'];
    await _utepedSdkPlugin.dFunc({'path':'device_options','method':'checkPermissions', 'permission':'p_storage'});
    print('permissions@@@  =====>>> : end');
  }

  Future<void> getImageWatchFace() async {
    print('getImageWatchFace@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "getImageWatchFace"});
    Map map = jsonDecode(info);
    print('getImageWatchFace###  =====>>> : $info/${map['mErrorCode']}');
  }

  Future<void> downloadImageWatchFace() async {
    print('downloadImageWatchFace@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "downloadImageWatchFace"});
    print('downloadImageWatchFace###  =====>>> : $info/}');
  }

  Future<void> setImageWatchFace() async {
    print('setImageWatchFace@@@  =====>>> : start');
    var info = await _utepedSdkPlugin
        .dFunc({"path": "watchFace", "method": "setImageWatchFace", 'type':2});
    print('setImageWatchFace###  =====>>> : $info/}');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Running on: $_platformVersion\n$isBluetoothEnable'),
              ElevatedButton(
                  onPressed: () => {connect()}, child: const Text('connect')),
              ElevatedButton(
                  onPressed: () => {test()}, child: const Text('test')),
              ElevatedButton(
                  onPressed: () => {download()}, child: const Text('download')),
              ElevatedButton(
                  onPressed: () => {uploadWatchFace()}, child: const Text('uploadWatchFace')),
              ElevatedButton(
                  onPressed: () => {applyWatchFace()}, child: const Text('applyWatchFace')),
              ElevatedButton(
                  onPressed: () => {getWatchFaceInfo()}, child: const Text('getWatchFaceInfo')),
              ElevatedButton(
                  onPressed: () => {getWatchFaceParams()}, child: const Text('getWatchFaceParams')),
              ElevatedButton(
                  onPressed: () => {permissions()}, child: const Text('permissions')),
              ElevatedButton(
                  onPressed: () => {getImageWatchFace()}, child: const Text('getImageWatchFace')),
              ElevatedButton(
                  onPressed: () => {downloadImageWatchFace()}, child: const Text('downloadImageWatchFace')),
              ElevatedButton(
                  onPressed: () => {setImageWatchFace()}, child: const Text('setImageWatchFace'))
            ],
          ),
        ),
      ),
    );
  }
}
